package com.swsc.solarverse.service.schedule;

import com.swsc.solarverse.common.util.LocalDateTimeUtils;
import com.swsc.solarverse.service.forward.IForwardStringDataCurrentdayService;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @Author CHENCL-X99
 * @Date 2025/5/14 11:47
 * @Version 1.0
 * @Description
 */
@lombok.extern.slf4j.Slf4j
@org.springframework.stereotype.Service
public class ForwardDataBackupScheduledService {
    private final IForwardStringDataCurrentdayService forwardStringDataCurrentdayService;

    public ForwardDataBackupScheduledService(IForwardStringDataCurrentdayService forwardStringDataCurrentdayService) {
        this.forwardStringDataCurrentdayService = forwardStringDataCurrentdayService;
    }

    public void copyYesterdayData2BeforeYesterday(LocalDateTime now) {
        forwardStringDataCurrentdayService.truncateBeforeYesterday();
        LocalDateTime start = LocalDateTimeUtils.getDayStart(now);
        LocalDateTime end = LocalDateTimeUtils.getDayStart(now);
        forwardStringDataCurrentdayService.copyYesterdayData2BeforeYesterday(start, end);
    }

    public void copyCurrentdayData2Yesterday(LocalDateTime now) {
        forwardStringDataCurrentdayService.truncateYesterday();
        LocalDateTime start = LocalDateTimeUtils.getDayStart(now);
        LocalDateTime end = LocalDateTimeUtils.getDayStart(now);
        forwardStringDataCurrentdayService.copyCurrentdayData2Yesterday(start, end);
    }

    @Transactional(rollbackFor = Exception.class)
    public void backupStringData(LocalDateTime now) {
        int cnt = forwardStringDataCurrentdayService.count();
        if(cnt <= 0) {
            log.info("数据备份-今天数据表中没有数据，无需备份");
            return;
        }
        log.info("数据备份-备份昨天数据表中的数据到前天数据表中-开始...");
        copyYesterdayData2BeforeYesterday(now);
        log.info("数据备份-备份昨天数据表中的数据到前天数据表中-完成...");

        log.info("数据备份-备份今天数据表中的数据到昨天数据表中-开始...");
        copyCurrentdayData2Yesterday(now);
        log.info("数据备份-备份今天数据表中的数据到昨天数据表中-完成...");
    }
}
